<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2022/1/27 15:04
 * Desc:票务产品处理
 */
class Model_Provider_Api_Ticket_Product
{
    private $provider_channel;

    const REFUND_RESTRICTION_NOT_LIMIT = 0; // 无条件
    const REFUND_RESTRICTION_CANNOT = 1; // 不允许
    const REFUND_RESTRICTION_CONDITIONAL = 2; // 有条件

    public static $refund_type_to_refund_restriction = [
        1 => self::REFUND_RESTRICTION_CONDITIONAL,
        2 => self::REFUND_RESTRICTION_CANNOT,
        3 => self::REFUND_RESTRICTION_CONDITIONAL
    ];

    public function __construct($providerChannel = '')
    {
        $this->provider_channel = $providerChannel;
    }

    public function save_spot($scenic)
    {
        $interfaceCode = Model_Provider_Api_Ticket::create_scenic_interface_code($scenic['scenicId'], $this->provider_channel);
        $spot = ORM::factory('spot')->where('interface_code', '=', $interfaceCode)->find();
        $nowTime = time();
        if (!$spot->id) {
            $spot->addtime = $nowTime;
            $spot->shownum = Model_Provider_Api_Tools::get_show_num();
            $spot->bookcount = Model_Provider_Api_Tools::get_book_count();
            $spot->satisfyscore = Model_Provider_Api_Tools::get_virtual_satisfy_score();
            $spot->aid = St_Functions::get_last_aid('sline_spot', 0);
        }
        // 需要处理的数据
        list($scenicImg, $litpic) = self::get_pic($scenic['scenicImg']);
        list($finalDestId, $kindList) = self::get_destination($scenic['cityName']);
        $spot->litpic = $litpic;
        $spot->piclist = $scenicImg;
        $spot->finaldestid = $finalDestId;
        $spot->kindlist = $kindList;
        // 直接数据
        $spot->webid = 0;
        $spot->title = $scenic['scenicName'];
        $spot->shortname = $scenic['scenicName'];
        $spot->address = $scenic['scenicAddress'];
        $spot->interface_code = $interfaceCode;
        $spot->modtime = $nowTime;
        // 额外数据
        if (isset($scenic['lng'])) {
            $spot->lng = $scenic['lng'];
        }
        if (isset($scenic['lat'])) {
            $spot->lat = $scenic['lat'];
        }
        if (isset($scenic['content'])) {
            $spot->content = $scenic['content'];
        }
        if (isset($scenic['open_time_des'])) {
            $spot->open_time_des = $scenic['open_time_des'];
        }
        if (isset($scenic['booknotice'])) {
            $spot->booknotice = $scenic['booknotice'];
        }
        $spot->save();
        if ($spot->saved()) {
            $spot->reload();
            return array('status' => true, 'spotId' => $spot->id);
        } else {
            return array('status' => false);
        }
    }

    // 获取门票列表
    public function get_ticket_list_by_scenic_id($params)
    {
        $api = new Model_Provider_Api_Ticket($params['partnerId'], $this->provider_channel);
        $params = array(
            'scenicId' => $params['scenicId'],
            'page' => isset($params['page']) ? $params['page'] : 1,
            'pagesize' => isset($params['pageSize']) ? $params['pageSize'] : 10,
            'needOriginalProductInfo' => true,
            'ota' => isset($params['ota']) ? $params['ota'] : '',
            'providerChannel' => $this->provider_channel,
        );
        $rtn = $api->product_list($params);
        if (isset($rtn['code']) && $rtn['code'] == 200) {
            return $rtn['data'];
        }
        return array();
    }

    public function save_ticket($ticket, $spotId, $supplierId = '')
    {
        $db = Database::instance();
        $db->begin();
        try {
            $interface_code = Model_Provider_Api_Ticket::create_ticket_interface_code($ticket['productId'], $this->provider_channel);
            $ticketModel = ORM::factory('spot_ticket')
                ->where('supplierlist', '=', $supplierId)
                ->and_where('interface_code', '=', $interface_code)
                ->find();
            // 基础数据
            $nowTime = time();
            if (!$ticketModel->id) {
                $ticketModel->addtime = $nowTime;
                $ticketModel->interface_code = $interface_code;
            }
            $ticketModel->supplierlist = $supplierId;
            $ticketModel->modtime = $nowTime;
            $ticketModel->spotid = $spotId;
            // 差异数据
            $ticketModel->title = $ticket['title'];
            $ticketModel->status = $ticket['status'];
            $ticketModel->ourprice = $ticket['ourprice'];
            $ticketModel->refund_restriction = $ticket['refund_restriction'];
            $ticketModel->fill_tourer_type = $ticket['fill_tourer_type'];
            $ticketModel->description = $ticket['description'];
            $ticketModel->sellprice = $ticket['marketPrice'];
            $ticketModel->fill_tourer_items = $ticket['fill_tourer_items'];
            $ticketModel->pay_way = isset($ticket['pay_way']) ? $ticket['pay_way'] : 1; // '支付方式  1 线上 2线下 3线上,线下均支持',
            $ticketModel->paytype = isset($ticket['paytype']) ? $ticket['paytype'] : 1; // 支付类型 1 全额 2 定金支付
            $ticketModel->get_ticket_way = isset($ticket['get_ticket_way']) ? $ticket['get_ticket_way'] : '';
            $typeName = isset($ticket['typeName']) && !empty($ticket['typeName']) ? $ticket['typeName'] : '普通票';
            $ticketModel->tickettypeid = Model_Provider_Api_Ticket_Product::create_spot_ticket_type($typeName, $spotId);
            $ticketModel->day_before = isset($ticket['day_before']) ? $ticket['day_before'] : 0;//提前预订天数
            $ticketModel->hour_before = $ticket['hour_before'] ? $ticket['hour_before'] : 0;//提前预订小时数
            $ticketModel->minute_before = $ticket['minute_before'] ? $ticket['minute_before'] : 0;//提前预订分钟数
            if(St_Functions::is_normal_app_install('mobiledistribution')){
                $ticketModel->fenxiao_status = DB::select('value')->from('fenxiao_config')->where('varname="cfg_main_fenxiao_status"')->execute()->get('value');
            }

            $ticketModel->save();
            if ($ticketModel->saved()) {
                $ticketModel->reload();
                $db->commit();
                return $ticketModel->id;
            } else {
                $db->rollback();
                return null;
            }
        } catch (Exception $ex) {
            Model_Tool_Log::write('supplier_provider.ticket_log', $ex);
            $db->rollback();
            return null;
        }
    }

    // 获取门票价格
    public function get_ticket_calender($params)
    {
        $api = new Model_Provider_Api_Ticket($params['partnerId'], $this->provider_channel);
        $calendarParams = array(
            'productId' => $params['productId'],
            'startTime' => $params['startTime'],
            'endTime' => $params['endTime'],
            'providerChannel' => $this->provider_channel,
        );
        $rtn = $api->product_calendar($calendarParams);
        if (isset($rtn['code']) && $rtn['code'] == 200) {
            return array('status' => true, 'msg' => '处理完成', 'data' => $rtn['data']);
        } else {
            return array('status' => false, 'msg' => '获取门票报价失败');
        }
    }

    // 产品变更
    public function product_change($params)
    {
        $api = new Model_Provider_Api_Ticket($params['partnerId'], $this->provider_channel);
        $params = array(
            'extendData' => $params['extendData'],
            'providerChannel' => $this->provider_channel,
        );
        $rtn = $api->product_change($params);
        if (isset($rtn['code']) && $rtn['code'] == 200) {
            return array('status' => true, 'msg' => '处理完成', 'data' => $rtn['data']);
        } else {
            return array('status' => false, 'msg' => $rtn['msg']);
        }
    }

    public function save_ticket_price(array $prices, $ticket)
    {
        //删除原有价格 以防部分老价格未被覆盖
        DB::delete('spot_ticket_price')->where('ticketid', '=', $ticket['id'])->execute();
        if (!empty($prices)) {
            $values = array();
            foreach ($prices as $price) {
                $day = strtotime($price['date']);
                $adultprofit = $price['price'] - $price['settlementPrice'];
                $adultprofit = $adultprofit > 0 ? $adultprofit : 0;
                $number = $price['stock'] == '999' ? -1 : $price['stock'];
                $values[] = "('{$ticket['spotid']}','{$ticket['id']}','{$day}','{$adultprofit}','{$price['settlementPrice']}','{$price['price']}','{$price['marketPrice']}','{$number}')";
            }
            if (!empty($values)) {
                $sql = 'INSERT INTO `sline_spot_ticket_price` (`spotid`,`ticketid`,`day`,`adultprofit`,`adultbasicprice`,`adultprice`,`adultmarketprice`,`number`) VALUES ';
                $sql .= implode(',', $values);
                $sql .= ' ON DUPLICATE KEY UPDATE `ticketid` = VALUES(`ticketid`),`day` = VALUES(`day`)';
                DB::query(Database::INSERT, $sql)->execute();
            }
        }
        return true;
    }

    public static function get_interface_code_by_ticket_id($ticket_id)
    {
        $ticket = DB::select('interface_code')
            ->from('spot_ticket')
            ->where('id', '=', $ticket_id)
            ->execute()
            ->current();
        if ($ticket && $ticket['interface_code']) {
            $interfaceCode = json_decode($ticket['interface_code'], true);
            if ($interfaceCode && isset($interfaceCode['comeFrom']) && isset($interfaceCode['productId'])) {
                return $interfaceCode;
            }
        }
        return null;
    }

    // 创建票务类型
    public static function create_spot_ticket_type($typeName, $spotId)
    {
        $model = ORM::factory('spot_ticket_type')
            ->where('spotid', '=', $spotId)
            ->and_where('kindname', '=', $typeName)
            ->find();
        if (!$model->id) {
            $model->kindname = $typeName;
            $model->spotid = $spotId;
            $model->save();
            if ($model->saved()) {
                $model->reload();
            } else {
                return '';
            }
        }
        return $model->id;
    }

    /**
     * 获取导入产品的日期
     * @param int $importMonth 需要导入的月份
     * @return array
     */
    public static function get_import_date($importMonth = 6)
    {
        $startTime = date("Y-m-d");
        $endTime = date("Y-m-d", strtotime("+{$importMonth} months", strtotime($startTime)));
        return array(
            'startTime' => $startTime,
            'endTime' => $endTime,
        );
    }

    /**
     * 根据城市名称获取目的地和最终目的地
     * @param $cityName
     * @return array
     */
    public static function get_destination($cityName)
    {
        // 目的地处理 $scenic['cityName']
        $finalDestId = '';
        $kindList = '';
        if ($cityName) {
            $finalDestId = Model_Provider_Destination::match_destination_id_by_keyword($cityName);
            if ($finalDestId) {
                $kindList = Model_Provider_Destination::destination_parents_id($finalDestId);
            }
        }
        return array($finalDestId, $kindList);
    }

    /**
     * 根据图片字符串获取图片封面
     * @param $scenicImg
     * @return array
     */
    public static function get_pic($scenicImg)
    {
        $litpic = '';
        $scenicImg = !empty($scenicImg) && is_string($scenicImg) ? $scenicImg : '';
        if ($scenicImg) {
            $scenicImgArr = explode(',', $scenicImg);
            $litpic = isset($scenicImgArr[0]) ? $scenicImgArr[0] : '';
        }
        return array($scenicImg, $litpic);
    }

    /**
     * 更新产品状态
     * @param $productId
     * @param $status
     * @throws Kohana_Exception
     */
    public function update_ticket_status($productId, $status)
    {
        $interface_code = Model_Provider_Api_Ticket::create_ticket_interface_code($productId, $this->provider_channel);
        $ticketModel = ORM::factory('spot_ticket')
            ->where(DB::expr('supplierlist is not null'))
            ->and_where('interface_code', '=', $interface_code)
            ->find();
        if($ticketModel->loaded()){
            $ticketModel->status = $status;
            $ticketModel->modtime = time();
            $ticketModel->save();
        }
    }
}